<%@page import="edu.cmu.aes.project2.UserInformationService"%>
<%@page import="edu.cmu.aes.project2.security.UISecurityUtil"%>
<%

	request.setAttribute("title", "Login Page");
	boolean isRedirect = UISecurityUtil.checkSecuredAccess(request,
			response);
	if (isRedirect) {
		return;
	}
	
	String errorMessage = "";
	
	if(request.getParameter("submit")!=null){

		String userName = request.getParameter("username");
		if(userName == null)
			userName = "";
		String password = request.getParameter("password");
		if(password == null)
			password = "";
		
		// Temporary Validation
		//if("mse".equals(userName) && "cmu".equals(password))
		//	isSuccess = true;
		UserInformationService userInfoService = new UserInformationService();
		Boolean result = userInfoService.authentication(userName, password);
		if(result == null){
			errorMessage = "Unexpected Error, please contact web master";
		}else if(result.booleanValue()){
			UISecurityUtil.registerLogin(request,userName);
			response.sendRedirect("index.jsp");
		}else{
			errorMessage = "Incorrect username or password";
		}
	}
	
%>
<%@include file='/WEB-INF/template/header.jsp'%>
<%@include file='/WEB-INF/template/right-menu.jsp'%>
<script type="text/javascript">
	function regIsDigit(fData)
	{
	    //var reg = new RegExp("^[0-9]$");
	    //return (reg.match(fData));
	    return fData.match(/^\d+$/) != null;
	}

	function validateLogin(){
		var username = $("#username").val();
		var password = $("#password").val();

		if(username.length == 0){
			alert("Please input username");
			return false;
		}
		if(password.length == 0){
			alert("Please input password");
			return false;
		}
		
		return true;
	}
</script>
<div id="content">
	<form name="login" method="post" action="login.jsp" onsubmit="return validateLogin();">
		<table>
		<%
		if(!"".equals(errorMessage)){
		%>
			<tr>
				<td colspan="2" class='error'><%=errorMessage %></td>
			</tr>
		<%	
		}
		%>
			<tr>
				<td width=80>Username</td>
				<td>: <input type="text" name="username" id="username"/>
				</td>
			</tr>
			<tr>
				<td>Password</td>
				<td>: <input type="password" name="password" id="password"/>
				</td>
			</tr>
			<tr>
				<td colspan="2" align="center"><input type="submit"
					name="submit" value="Login" />
				</td>
			</tr>
		</table>
	</form>
</div>
<%@include file='/WEB-INF/template/footer.jsp'%>